package com.flyco.modules.oms.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.flyco.common.aspect.annotation.AutoLog;
import com.flyco.common.exception.FlycoException;
import com.flyco.common.system.vo.LoginUser;
import com.flyco.common.util.IPUtils;
import com.flyco.common.util.RedisUtil;
import com.flyco.common.util.address.AddressUtil;
import com.flyco.common.util.address.WSSsdrAddress;
import com.flyco.modules.oms.entity.*;
import com.flyco.modules.oms.model.*;
import com.flyco.modules.oms.service.*;
import com.flyco.common.util.CustomerExcelExportStyler;
import com.flyco.modules.oms.vo.OmsOrderImportPage;
import com.flyco.modules.pms.entity.*;
import com.flyco.modules.pms.service.*;
import com.flyco.modules.pms.vo.PmsProductSkuForOrderVO;
import com.flyco.modules.stm.entity.*;
import com.flyco.modules.stm.mapper.PmsBoxTraceRecordMapper;
import com.flyco.modules.stm.service.*;
import com.flyco.modules.system.service.ISysDictService;
import com.flyco.modules.task.service.SapTaskService;
import com.flyco.modules.ums.entity.UmsMember;
import com.flyco.modules.ums.service.IUmsMemberService;
import com.google.common.base.Joiner;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import com.flyco.poi.excel.ExcelImportUtil;
import com.flyco.poi.excel.def.NormalExcelConstants;
import com.flyco.poi.excel.entity.ExportParams;
import com.flyco.poi.excel.entity.ImportParams;
import com.flyco.poi.excel.view.EntityExcelView;

import com.flyco.common.api.vo.Result;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.oms.vo.OmsOrderPage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 订单管理
 * @Author: flyco
 * @Date: 2019-12-10
 * @Version: V1.0
 */
@Api(tags = "订单")
@RestController
@RequestMapping("/f/oms/omsOrder")
@Slf4j
public class OmsOrderController {
    @Autowired
    private IOmsOrderService omsOrderService;
    @Autowired
    private IOmsOrderItemService omsOrderItemService;
    @Autowired
    private IOmsOrderInvoiceService omsOrderInvoiceService;
    @Autowired
    private ISysDictService dictService;
    @Resource
    private SapTaskService sapTaskService;
    @Autowired
    private IOmsOrderTraceService omsOrderTraceService;
    @Autowired
    private PmsBoxTraceRecordMapper pmsBoxTraceRecordMapper;
    @Autowired
    private IPmsBoxTraceService pmsBoxTraceService;
    @Autowired
    private IOmsOrderCancelService omsOrderCancelService;
    @Autowired
    private IStmStoreInfoService stmStoreInfoService;
    @Autowired
    private IOmsOrderBatchService omsOrderBatchService;
    @Autowired
    private IPmsProductService pmsProductService;
    @Autowired
    private IUmsMemberService umsMemberService;
    @Autowired
    private IOmsOrderAdditionService omsOrderAdditionService;
    @Autowired
    private IPmsProductPriceRegulateService pmsProductPriceRegulateService;
    @Autowired
    private IStmBizInoutRelationService stmBizInoutRelationService;
    @Autowired
    private IStmChannelInfoService channelInfoService;
    @Autowired
    private IStmStoreInfoService storeInfoService;
    @Autowired
    private IStmJdWmsStockService wmsStockService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IStmStoreProductStockService productStockService;
    @Autowired
    private IOmsOrderSettingService omsOrderSettingService;
    @Autowired
    private IOmsOrderDiscountRecordService omsOrderDiscountRecordService;

    /**
     * 分页列表查询
     *
     * @param omsOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "订单-分页列表查询")
    @ApiOperation(value = "订单-分页列表查询", notes = "订单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(OmsOrder omsOrder,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        omsOrder.setPartnerId(sysUser.getPartnerId());
        if (omsOrder.getCompanyName() != null && omsOrder.getCompanyName().indexOf("*") == -1) {
            omsOrder.setCompanyName("*" + omsOrder.getCompanyName() + "*");
        }
        List<Integer> inStatusList = new ArrayList<>();
        if (omsOrder.getStatus() != null && omsOrder.getStatus().equals(1)) {
            inStatusList.add(1);
            inStatusList.add(11);
            omsOrder.setStatus(null);
        }
        List<Integer> statusList = new ArrayList<>();
        statusList.add(4);
        statusList.add(8);

        QueryWrapper<OmsOrder> queryWrapper = QueryGenerator.initQueryWrapper(omsOrder, req.getParameterMap());
        queryWrapper.ne("store_id", 0);
        queryWrapper.ne("delete_status", 1);
        if (StringUtils.isEmpty(omsOrder.getOrderType())) {
            queryWrapper.in("order_type", 0, 1);
        }
        if (!StringUtils.isEmpty(omsOrder.getSaleUserName())) {
            queryWrapper.eq("sale_user_name", omsOrder.getSaleUserName());
        }
        //默认过滤取消和退回状态的订单
        if (!statusList.contains(omsOrder.getStatus())) {
            queryWrapper.notIn("status", statusList);
        }

        //如果筛选复审的时候，把已复审未提货的也带出来
        if (!inStatusList.isEmpty()) {
            queryWrapper.in("status", inStatusList);
        }
        queryWrapper.orderByDesc("id");
        Page<OmsOrder> page = new Page<OmsOrder>(pageNo, pageSize);
        IPage<OmsOrder> pageList = omsOrderService.page(page, queryWrapper);
        if (pageList.getTotal() > 0) {
            List<Long> storeIdList = pageList.getRecords().stream().map(OmsOrder::getStoreId).collect(Collectors.toList());
            List<StmStoreInfo> storeInfoList = stmStoreInfoService.getStoreInfoList(storeIdList);
            pageList.getRecords().forEach(order -> {
                if (oConvertUtils.isNotEmpty(order.getStoreId())) {
                    if (!storeInfoList.isEmpty()) {
                        List<StmStoreInfo> resultList = storeInfoList.stream().filter(s -> s.getStoreId().equals(order.getStoreId())).collect(Collectors.toList());
                        if (!resultList.isEmpty()) {
                            order.setStoreId_dictText(resultList.get(0).getName());
                        }
                    }
                }
            });
        }
        return Result.ok(pageList);
    }


    /**
     * 直播订单分页列表查询
     *
     * @param omsOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "订单-直播分页列表查询")
    @ApiOperation(value = "订单-直播分页列表查询", notes = "订单-直播分页列表查询")
    @GetMapping(value = "/liveList")
    public Result<?> queryLivePageList(OmsOrder omsOrder,
                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                       HttpServletRequest req) {
        QueryWrapper<OmsOrder> queryWrapper = QueryGenerator.initQueryWrapper(omsOrder, req.getParameterMap());
        queryWrapper.orderByDesc("id");
        Page<OmsOrder> page = new Page<OmsOrder>(pageNo, pageSize);
        IPage<OmsOrder> pageList = omsOrderService.getLiveOrderPage(page, queryWrapper);
        if (pageList.getTotal() > 0) {
            List<StmStoreInfo> storeInfos = stmStoreInfoService.list();
            Map<Long, String> storeInfoMaps = storeInfos.stream().collect(Collectors.toMap(StmStoreInfo::getStoreId, StmStoreInfo::getName, (key1, key2) -> key2));
            pageList.getRecords().forEach(stock -> {
                if (oConvertUtils.isNotEmpty(stock.getStoreId())) {
                    if (storeInfoMaps.containsKey(stock.getStoreId())) {
                        stock.setStoreId_dictText(storeInfoMaps.get(stock.getStoreId()));
                    } else {
                        if (Objects.equals(0L, stock.getStoreId())) {
                            stock.setStoreId_dictText("线上商城");
                        }
                    }
                }
            });
        }
        return Result.ok(pageList);
    }

    /**
     * 内购订单分页列表查询
     *
     * @param omsOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "订单-内购分页列表查询")
    @ApiOperation(value = "订单-内购分页列表查询", notes = "订单-内购分页列表查询")
    @GetMapping(value = "/innerList")
    public Result<?> queryInnerPageList(OmsOrder omsOrder,
                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                        HttpServletRequest req) {
        QueryWrapper<OmsOrder> queryWrapper = QueryGenerator.initQueryWrapper(omsOrder, req.getParameterMap());
        queryWrapper.orderByDesc("id");
        Page<OmsOrder> page = new Page<OmsOrder>(pageNo, pageSize);
        IPage<OmsOrder> pageList = omsOrderService.getInnerOrderPage(page, queryWrapper);
        Page<OmsOrderPage> orderPage = new Page<OmsOrderPage>(pageNo, pageSize);
        List<OmsOrderPage> orderPages = new ArrayList<OmsOrderPage>();
        if (pageList.getTotal() > 0) {
            List<StmStoreInfo> storeInfos = stmStoreInfoService.list();
            Map<Long, String> storeInfoMaps = storeInfos.stream().collect(Collectors.toMap(StmStoreInfo::getStoreId, StmStoreInfo::getName, (key1, key2) -> key2));
            pageList.getRecords().forEach(order -> {
                if (oConvertUtils.isNotEmpty(order.getStoreId())) {
                    if (storeInfoMaps.containsKey(order.getStoreId())) {
                        order.setStoreId_dictText(storeInfoMaps.get(order.getStoreId()));
                    } else {
                        if (Objects.equals(0L, order.getStoreId())) {
                            order.setStoreId_dictText("线上商城");
                        }
                    }
                }
                OmsOrderPage omsOrderPage = BeanUtils.instantiateClass(OmsOrderPage.class);
                BeanUtils.copyProperties(order, omsOrderPage);
                List<OmsOrderItem> omsOrderItemList = omsOrderItemService.selectByMainId(order.getId());
                omsOrderPage.setOmsOrderItemList(omsOrderItemList);
                orderPages.add(omsOrderPage);
            });
        }
        IPage<OmsOrderPage> orderPageList = orderPage.setRecords(orderPages);
        orderPageList.setTotal(pageList.getTotal());
        return Result.ok(orderPageList);
    }

    /**
     * 团购订单分页列表查询
     *
     * @param omsOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "订单-团购分页列表查询")
    @ApiOperation(value = "订单-团购分页列表查询", notes = "订单-团购分页列表查询")
    @GetMapping(value = "/groupBuyList")
    public Result<?> queryGroupBuyPageList(OmsOrder omsOrder,
                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                           HttpServletRequest req) {
        QueryWrapper<OmsOrder> queryWrapper = QueryGenerator.initQueryWrapper(omsOrder, req.getParameterMap());
        queryWrapper.orderByDesc("id");
        Page<OmsOrder> page = new Page<OmsOrder>(pageNo, pageSize);
        IPage<OmsOrder> pageList = omsOrderService.getGroupBuyOrderPage(page, queryWrapper);
        Page<OmsOrderPage> orderPage = new Page<OmsOrderPage>(pageNo, pageSize);
        List<OmsOrderPage> orderPages = new ArrayList<OmsOrderPage>();
        if (pageList.getTotal() > 0) {
            List<StmStoreInfo> storeInfos = stmStoreInfoService.list();
            Map<Long, String> storeInfoMaps = storeInfos.stream().collect(Collectors.toMap(StmStoreInfo::getStoreId, StmStoreInfo::getName, (key1, key2) -> key2));
            pageList.getRecords().forEach(order -> {
                if (oConvertUtils.isNotEmpty(order.getStoreId())) {
                    if (storeInfoMaps.containsKey(order.getStoreId())) {
                        order.setStoreId_dictText(storeInfoMaps.get(order.getStoreId()));
                    } else {
                        if (Objects.equals(0L, order.getStoreId())) {
                            order.setStoreId_dictText("线上商城");
                        }
                    }
                }
                OmsOrderPage omsOrderPage = BeanUtils.instantiateClass(OmsOrderPage.class);
                BeanUtils.copyProperties(order, omsOrderPage);
                List<OmsOrderItem> omsOrderItemList = omsOrderItemService.selectByMainId(order.getId());
                omsOrderPage.setOmsOrderItemList(omsOrderItemList);
                orderPages.add(omsOrderPage);
            });
        }
        IPage<OmsOrderPage> orderPageList = orderPage.setRecords(orderPages);
        orderPageList.setTotal(pageList.getTotal());
        return Result.ok(orderPageList);
    }

    /**
     * 添加
     *
     * @param omsOrderPage
     * @return
     */
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody OmsOrderPage omsOrderPage) {
        OmsOrder omsOrder = new OmsOrder();
        BeanUtils.copyProperties(omsOrderPage, omsOrder);
        omsOrderService.saveMain(omsOrder, omsOrderPage.getOmsOrderItemList(), omsOrderPage.getOmsOrderInvoiceList());
        return Result.ok("添加成功!");
    }

    /**
     * 订单补发
     *
     * @param omsOrderPage
     * @return
     */
    @PostMapping(value = "/addOmsOrder")
    public Result<?> addOmsOrder(@RequestBody OmsOrderPage omsOrderPage) {
        if (CollectionUtils.isEmpty(omsOrderPage.getOmsOrderItemList())) {
            return Result.error("没有订单明细，无法创建订单!");
        }
        omsOrderPage.setOrderSource(1);
        omsOrderPage.setOrderType(1);
        omsOrderService.addOmsOrder(omsOrderPage, true, true);
        return Result.ok("后台补发订单添加成功!");
    }


    /**
     * 订单审核（通过或者决绝）
     *
     * @param omsOrderPage
     * @return
     */
    @ApiOperation(value = "订单审核", notes = "订单审核")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody OmsOrderPage omsOrderPage) {
        if (StrUtil.isBlank(omsOrderPage.getId()) || omsOrderPage.getStatus() == null || !Arrays.asList(1, 4).contains(omsOrderPage.getStatus())) {
            return Result.fail("参数不正确");
        }
        if (omsOrderPage.getStatus() == 4 && StrUtil.isBlank(omsOrderPage.getNote())) {
            return Result.fail("审核不通过原因必须填写");
        }

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        OmsOrder omsOrder = new OmsOrder();
        omsOrder.setId(omsOrderPage.getId());
        omsOrder.setStatus(omsOrderPage.getStatus());
        omsOrder.setApplyTime(new Date());
        omsOrder.setApplyBy(sysUser.getRealname());
        boolean update = omsOrderService.update(omsOrder, Wrappers.lambdaUpdate(OmsOrder.class).eq(OmsOrder::getId, omsOrder.getId()).eq(OmsOrder::getCancelFlag, 0).eq(OmsOrder::getStatus, 0));
        if (!update) {
            return Result.fail("数据过期，请刷新页面重试");
        }

        OmsOrderTrace omsOrderTrace = new OmsOrderTrace();
        omsOrderTrace.setOrderId(omsOrder.getId());
        omsOrderTrace.setCreateTime(new Date());
        if (omsOrder.getStatus() == 1) {
            omsOrderTrace.setLabel("审核通过");
            omsOrderTrace.setContent("您的订单已审核通过，请线下对公转账");


        } else if (omsOrder.getStatus() == 4) {
            omsOrderTrace.setLabel("审核不通过：" + omsOrderPage.getNote());
            omsOrderTrace.setContent(omsOrderPage.getNote());
        }
        omsOrderTraceService.save(omsOrderTrace);
        return Result.ok("操作成功!");
    }


    /**
     * 订单审核（通过或者决绝）
     *
     * @param omsOrderPage
     * @return
     */
    @ApiOperation(value = "修改订单备注", notes = "修改订单备注")
    @PostMapping(value = "/editRemark")
    public Result<?> editRemark(@RequestBody OmsOrderPage omsOrderPage) {
        OmsOrder omsOrder = new OmsOrder();
        omsOrder.setId(omsOrderPage.getId());
        omsOrder.setRemark(omsOrderPage.getRemark());
        boolean update = omsOrderService.update(omsOrder, Wrappers.lambdaUpdate(OmsOrder.class).eq(OmsOrder::getId, omsOrder.getId()));
        if (!update) {
            return Result.fail("数据过期，请刷新页面重试");
        }
        OmsOrderTrace omsOrderTrace = new OmsOrderTrace();
        omsOrderTrace.setOrderId(omsOrder.getId());
        omsOrderTrace.setCreateTime(new Date());
        omsOrderTrace.setLabel("修改订单备注");
        omsOrderTrace.setContent(omsOrderPage.getRemark());
        omsOrderTraceService.save(omsOrderTrace);
        return Result.ok("操作成功!");
    }

    /**
     * 订单审核通过后，增加门店商品购买数量
     * type 1:订单审核通过时传，需要增加购买数量， 取消订单时传2 需要扣除购买数量
     */
    public void updateProductStock(String orderId, Integer type) {

        List<OmsOrderItem> orderItemList = omsOrderItemService.selectByMainId(orderId);
        OmsOrder orderInfo = omsOrderService.getById(orderId);
        for (OmsOrderItem item : orderItemList) {
            Integer count = type == 1 ? item.getProductQuantity() : -item.getProductQuantity();
            productStockService.updateStock(orderInfo.getStoreId(), item.getProductId(), count);
        }
    }


    /**
     * 编辑物流信息
     */
    @AutoLog(value = "订单-修改物流信息")
    @ApiOperation(value = "订单-修改物流信息")
    @PutMapping(value = "/editAddress")
    public Result<?> editAddress(@RequestBody OmsOrder vueOrder) {
        if (StrUtil.isBlank(vueOrder.getId()) || StrUtil.isBlank(vueOrder.getDeliveryCompany()) || StrUtil.isBlank(vueOrder.getDeliverySn())) {
            return Result.fail("参数不能为空");
        }

        OmsOrder omsOrder = new OmsOrder();
        omsOrder.setDeliveryCompany(vueOrder.getDeliveryCompany());
        omsOrder.setDeliverySn(vueOrder.getDeliverySn());
        omsOrder.setRemark(vueOrder.getRemark());
        omsOrder.setStatus(2);
        Boolean b = omsOrderService.update(omsOrder, Wrappers.lambdaUpdate(OmsOrder.class)
                .eq(OmsOrder::getId, vueOrder.getId())
                .eq(OmsOrder::getPayStatus, 4));
        if (!b) {
            return Result.error("修改物流信息失败");
        }

        if (true) {
            OmsOrderTrace omsOrderTrace = omsOrderTraceService.getOne(new LambdaQueryWrapper<OmsOrderTrace>().eq(OmsOrderTrace::getOrderId, vueOrder.getId()).eq(OmsOrderTrace::getLabel, "发货确认"));
            if (omsOrderTrace != null) {
                omsOrderTrace.setLabel("发货确认");
                omsOrderTrace.setContent("物流公司:" + vueOrder.getDeliveryCompany() + " 物流单号:" + vueOrder.getDeliverySn());
                omsOrderTraceService.updateById(omsOrderTrace);
            } else {
                omsOrderTrace = new OmsOrderTrace();
                omsOrderTrace.setOrderId(vueOrder.getId());
                omsOrderTrace.setCreateTime(new Date());
                omsOrderTrace.setLabel("发货确认");
                omsOrderTrace.setContent("物流公司:" + vueOrder.getDeliveryCompany() + " 物流单号:" + vueOrder.getDeliverySn());
                omsOrderTraceService.save(omsOrderTrace);
            }
        }

        return Result.ok("修改物流信息成功!");
    }


    /**
     * 编辑物流信息
     */
/*    @AutoLog(value = "订单-发货")
    @PutMapping(value = "/editdeliverySn")
    public Result<?> editdeliverySn(@RequestBody OmsOrder vueOrder) {
        if (StrUtil.isBlank(vueOrder.getId()) || StrUtil.isBlank(vueOrder.getDeliveryCompany()) || StrUtil.isBlank(vueOrder.getDeliverySn())) {
            return Result.fail("参数不能为空");
        }
        OmsOrder omsOrder = new OmsOrder();
        omsOrder.setDeliveryCompany(vueOrder.getDeliveryCompany());
        omsOrder.setDeliverySn(vueOrder.getDeliverySn());
        Boolean b = omsOrderService.update(omsOrder, Wrappers.lambdaUpdate(OmsOrder.class)
                .eq(OmsOrder::getId, vueOrder.getId())
                .eq(OmsOrder::getStatus, 2).eq(OmsOrder::getPayStatus, 4));
        if (!b) {
            return Result.error("修改物流信息失败");
        }

        if (true) {
            OmsOrderTrace omsOrderTrace = omsOrderTraceService.getOne(new LambdaQueryWrapper<OmsOrderTrace>().eq(OmsOrderTrace::getOrderId, vueOrder.getId()).eq(OmsOrderTrace::getLabel, "发货确认"));
            if (omsOrderTrace != null) {
                omsOrderTrace.setLabel("发货确认");
                omsOrderTrace.setContent("物流公司:" + vueOrder.getDeliveryCompany() + " 物流单号:" + vueOrder.getDeliverySn());
                omsOrderTraceService.updateById(omsOrderTrace);
            } else {
                omsOrderTrace = new OmsOrderTrace();
                omsOrderTrace.setOrderId(vueOrder.getId());
                omsOrderTrace.setCreateTime(new Date());
                omsOrderTrace.setLabel("发货确认");
                omsOrderTrace.setContent("物流公司:" + vueOrder.getDeliveryCompany() + " 物流单号:" + vueOrder.getDeliverySn());
                omsOrderTraceService.save(omsOrderTrace);
            }
        }

        return Result.ok("修改物流信息成功!");
    }*/

    /**
     * 通过时间挂起订单
     *
     * @param vueOrder
     * @return
     */
    @AutoLog(value = "订单-通过截止时间挂起订单")
    @ApiOperation(value = "订单-通过截止时间挂起订单", notes = "订单-通过截止时间挂起订单")
    @PutMapping(value = "/editLockTime")
    public Result<?> editLockTime(@RequestBody OmsOrder vueOrder) {
        log.info("id:" + vueOrder.getId());
        OmsOrder originalOrder = omsOrderService.getById(vueOrder.getId());
        if ((originalOrder.getStatus() == 0 || originalOrder.getStatus() == 1) && (originalOrder.getProductStatus() == 1 || originalOrder.getProductStatus() == 2)) {
            OmsOrder order = new OmsOrder();
            order.setLockTime(DateUtil.offsetMinute(new Date(), 5));
            LambdaQueryWrapper<OmsOrder> query = new LambdaQueryWrapper<>();
            query.eq(OmsOrder::getId, originalOrder.getId());
            query.in(OmsOrder::getStatus, Arrays.asList(0, 1));
            query.in(OmsOrder::getProductStatus, Arrays.asList(1, 2));
            Boolean b = omsOrderService.update(order, query);
            if (b) {
                return Result.ok("临时挂起成功!");
            }
        }
        return Result.error("挂起失败");
    }


    /**
     * 通过状态挂起订单
     *
     * @param vueOrder
     * @return
     */
    @AutoLog(value = "订单-通过状态挂起订单")
    @ApiOperation(value = "订单-通过状态挂起订单", notes = "订单-通过状态挂起订单")
    @PutMapping(value = "/editLockStatus")
    public Result<?> editLockStatus(@RequestBody OmsOrder vueOrder) {
        OmsOrder originalOrder = omsOrderService.getById(vueOrder.getId());
        if ((originalOrder.getStatus() == 0 || originalOrder.getStatus() == 1) && (originalOrder.getProductStatus() == 1 || originalOrder.getProductStatus() == 2)) {
            OmsOrder order = new OmsOrder();
            order.setLockStatus(1);
            LambdaQueryWrapper<OmsOrder> query = new LambdaQueryWrapper<>();
            query.eq(OmsOrder::getId, originalOrder.getId());
            query.in(OmsOrder::getStatus, Arrays.asList(0, 1));
            query.in(OmsOrder::getProductStatus, Arrays.asList(1, 2));
            Boolean b = omsOrderService.update(order, query);
            if (b) {
                return Result.ok("状态挂起成功!");
            }
        }
        return Result.error("挂起失败");
    }


    /**
     * 订单改数量、审核：7 跟单员审核、10 物流审核、9 财务审核
     *
     * @param orderVO
     * @return
     */
    @AutoLog(value = "订单改数量，审批")
    @PutMapping(value = "/orderApprove")
    @Transactional
    public Result<?> orderApprove(@RequestBody OmsOrderModel orderVO) {
        if (StrUtil.isBlank(orderVO.getOrderId()) || orderVO.getStatus() == null || !Arrays.asList(1, 8).contains(orderVO.getStatus())) {
            return Result.error("参数不能为空!");
        }
        if (orderVO.getStatus() == 8 && StrUtil.isBlank(orderVO.getNote())) {
            return Result.fail("审核不通过原因必须填写！");
        }
        OmsOrder order = omsOrderService.getById(orderVO.getOrderId());
        if (null == order || !(order.getStatus().equals(0) || order.getCancelFlag().equals(1))) {
            return Result.error("当前状态不可审批！");
        }
        Result result = new Result();
        boolean needCalculateOrderAmount = false;

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //审核拒绝。修改订单状态，然后返回
        if (orderVO.getStatus() == 8) {
            order.setStatus(8);
            order.setUpdateTime(new Date());
            omsOrderService.updateById(order);
            saveOrderTrace(orderVO, sysUser);
            return result.ok("审核完成！");
        }

        //查询订单配置
        OmsOrderSetting orderSetting = omsOrderSettingService.getOne();
        List<OmsOrderItem> orderItemList = omsOrderItemService.selectByMainId(orderVO.getOrderId());

        //不允许超余额审单，判断余额是否大于订单应付金额
        if (orderSetting != null && orderSetting.getOrderAuditBalanceFlag() == 0) {
            StmStoreInfo storeInfo = storeInfoService.getByStoreId(order.getStoreId());
            List<OmsOrderItem> itemList = orderVO.getItemMap().values().stream().collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(itemList)) {
                BigDecimal totalAmount = BigDecimal.ZERO;
                for (OmsOrderItem item : itemList) {
                    totalAmount = totalAmount.add(item.getNeedPayAmount());
                }
                if (storeInfo.getRemainCreditLimit().compareTo(totalAmount) < 0) {
                    return Result.error("经销商余额不足，无法审批！");
                }
            }
        }

        //不允许无库存审单，判断库存是否足够
        if (orderSetting != null && orderSetting.getOrderAuditStockFlag() == 0) {
            //提交上来的表单数据
            List<OmsOrderItem> itemVOList = orderVO.getItemMap().values().stream().collect(Collectors.toList());
            //查询当前系统已初审单据占用库存
            List<OmsOrderItem> occupyItemList = omsOrderItemService.getProductOccupation(order.getId(), order.getPartnerId());
            //当前订单里面所有商品的skucode
            List<String> skuCodeList = orderItemList.stream().map(OmsOrderItem::getProductSkuCode).collect(Collectors.toList());
            //查询当前订单所有商品的库存
            List<StmJdWmsStock> skuStockList = wmsStockService.getBySkuCodeList(skuCodeList, order.getPartnerId());
            if (!CollectionUtils.isEmpty(orderItemList)) {
                for (OmsOrderItem item : orderItemList) {
                    StmJdWmsStock wmsStock = skuStockList.stream().filter(t -> t.getSkuCode().equals(item.getProductSkuCode())).findFirst().orElse(null);
                    Integer sendProQty = itemVOList.stream().filter(x -> x.getId().equals(item.getId())).findFirst().get().getSendProQty();
                    Integer occupyQty = 0;
                    OmsOrderItem occupyItem = occupyItemList.stream().filter(x -> x.getProductSkuCode().equals(item.getProductSkuCode())).collect(Collectors.toList()).stream().findFirst().orElse(null);
                    if (occupyItem != null) {
                        occupyQty = occupyItem.getSendProQty();
                    }
                    if (wmsStock == null || (wmsStock.getStock() - occupyQty < sendProQty)) {
                        return Result.error(item.getProductName() + "：库存不足，无法审批！");
                    }
                }
            }
        }

        //找出需要改价,改数量的商品
        //20240327增加逻辑，使用新字段存储分配的数量和价格，所以这里一定有值
        List<OmsOrderItem> collect = orderItemList.stream().filter(q -> orderVO.getItemMap().get(q.getId()) != null || orderVO.getItemMap().get(-q.getId()) != null).collect(Collectors.toList());
        if (!collect.isEmpty()) {
            needCalculateOrderAmount = true;
            //订单明细改数量
            result = updateOrderItemQuantity(collect, orderVO);
            if (!result.isSuccess()) {
                return result;
            }
        }

        //订单主表改价
        result = updateOrder(orderVO, sysUser, needCalculateOrderAmount, order);

        if (!result.isSuccess()) {
            return result;
        }

        //因为系统不需要确认付款，商家会在一个时间点统一付款。而现在有付款状态，所以这一步也一并通过
        if (orderVO.getStatus().equals(1)) {
            omsOrderService.payment(orderVO.getOrderId(), sysUser);
            // 当状态是1 ，表示财务也审核通过，需要增加商品购买数量
            //updateProductStock(orderVO.getOrderId(), 1);
        }

        //记录订单准状态修改信息
        result = saveOrderTrace(orderVO, sysUser);

        return result;
    }


    /**
     * 反审核，将订单状态更新为0，并调用接口通知sap取消订单
     *
     * @param orderVO
     * @return
     */
    @AutoLog(value = "反审核")
    @PutMapping(value = "/antiApprove")
    @Transactional
    public Result<?> antiApprove(@RequestBody OmsOrder orderVO) {
        OmsOrder order = omsOrderService.getById(orderVO.getId());
        if (null == order) {
            return Result.error("订单不存在！");
        }
        //撤销初审
        if (orderVO.getStatus() == 0 && !StringUtils.isEmpty(order.getVbeln())) {
            return Result.error("订单已经复审，不可撤销初审！");
        }
        //撤销初审
        if (orderVO.getStatus() == 0 && order.getStatus() != 5) {
            return Result.error("当前状态不可撤销初审！");
        }
        //反审核
        if (orderVO.getStatus() == 1 && order.getStatus() != 1) {
            return Result.error("当前状态不可反审核！");
        }

        //获取订单配置看是否要推送sap
        OmsOrderSetting orderSetting = omsOrderSettingService.getOne();
        if (orderSetting != null && orderSetting.getToSapFlag() == 1) {
            //如果还没推sap反审不需要调用sap接口
            if (!StringUtils.isEmpty(order.getVbeln())) {
                /* by martin 2024-05-22 反审核调用sap接口**/
                if (!"S".equalsIgnoreCase(sapTaskService.toSapOrderCancel(order.getId()).get("type"))) {
                    throw new FlycoException("反审核sap订单失败");
                }
            }
        }

        //by martin 2024-04-03 订单反审核后字段赋值为空，vbeln不为空重新审核sap报错
        omsOrderService.antiApprove(order);

        //记录订单准状态修改信息
        OmsOrderTrace omsOrderTrace = new OmsOrderTrace();
        omsOrderTrace.setOrderId(orderVO.getId());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        omsOrderTrace.setCreateBy(sysUser.getRealname());
        omsOrderTrace.setCreateTime(new Date());
        if (orderVO.getStatus() == 0) {
            omsOrderTrace.setLabel("订单撤销初审");
            omsOrderTrace.setContent("你的订单已撤销初审，操作人：" + sysUser.getRealname());
        } else {
            omsOrderTrace.setLabel("订单反审核");
            omsOrderTrace.setContent("你的订单已反审核，操作人：" + sysUser.getRealname());
        }
        omsOrderTraceService.save(omsOrderTrace);
        return Result.ok();
    }

    /**
     * 修改商品数量
     *
     * @return
     */
    private Result updateOrderItemQuantity(List<OmsOrderItem> collect, OmsOrderModel orderVO) {
        List<OmsOrderItem> changeItems = collect.stream().map(orderItem -> {
            OmsOrderItem changeItem = new OmsOrderItem();
            changeItem.setId(orderItem.getId());
            OmsOrderItem newItemOrg = (OmsOrderItem) orderVO.getItemMap().get(-orderItem.getId());
            OmsOrderItem itemOrg = (OmsOrderItem) orderVO.getItemMap().get(orderItem.getId());
            if (itemOrg != null) {
                if (newItemOrg != null) {
                    //有赠品
                    itemOrg.setGiftQuantity(newItemOrg.getProductQuantity());
                    itemOrg.setProductQuantity(itemOrg.getProductQuantity() + newItemOrg.getProductQuantity());
                } else {
                    //没有赠品时
                    itemOrg.setGiftQuantity(orderItem.getGiftQuantity());
                    itemOrg.setProductQuantity(orderItem.getMinUnitQuantity());
                    itemOrg.setSendProQty(itemOrg.getSendProQty() + orderItem.getGiftQuantity());
                }
            } else if (itemOrg == null) {
                itemOrg = orderItem;
                if (newItemOrg != null) {
                    Integer gift = itemOrg.getGiftQuantity() - newItemOrg.getProductQuantity();
                    itemOrg.setGiftQuantity(newItemOrg.getProductQuantity());
                    itemOrg.setProductQuantity(itemOrg.getProductQuantity() - gift);
                }
            }
            changeItem.setPromotionName("后台分配商品数量：" + itemOrg.getSendProQty());
            changeItem.setSendQty(itemOrg.getSendQty());//整箱数量
            changeItem.setSendProQty(itemOrg.getSendProQty());//商品只数
            changeItem.setGiftQuantity(itemOrg.getGiftQuantity());
            changeItem.setTotalRealAmount(itemOrg.getNeedPayAmount());//前端已经计算好应付金额
            changeItem.setTotalProductAmount(itemOrg.getTotalProductAmount());

            //判断应付金额是否存在负数
            if (itemOrg.getNeedPayAmount().compareTo(BigDecimal.ZERO) < 0) {
                throw new FlycoException("设置错误，部分商品存在应付金额<0的情况");
            }

            //判断有数量但是金额为0的情况
            if (changeItem.getSendProQty() > 0 && changeItem.getTotalRealAmount().compareTo(BigDecimal.ZERO) == 0) {
                throw new FlycoException("设置错误，部分商品存在有数量，应付金额为0的情况");
            }

            changeItem.setProductDiscountRate(itemOrg.getProductDiscountRate());
            changeItem.setProductDiscountAmount(itemOrg.getProductDiscountAmount());

            changeItem.setPromotionDiscountRate(itemOrg.getPromotionDiscountRate());
            changeItem.setPromotionDiscountAmount(itemOrg.getPromotionDiscountAmount());

            changeItem.setMissionDiscountRate(itemOrg.getMissionDiscountRate());
            changeItem.setMissionDiscountAmount(itemOrg.getMissionDiscountAmount());

            changeItem.setAdjustDiscountRate(itemOrg.getAdjustDiscountRate());
            changeItem.setAdjustDiscountAmount(itemOrg.getAdjustDiscountAmount());
            //固定折扣比例金额
            changeItem.setFixedDiscountRate(itemOrg.getFixedDiscountRate());
            changeItem.setFixedDiscountAmount(itemOrg.getFixedDiscountAmount());

            if (itemOrg.getMinUnitPrice() != null && itemOrg.getMinUnitPrice().compareTo(BigDecimal.ZERO) > 0) {
                changeItem.setProductPrice(itemOrg.getMinUnitPrice());
                changeItem.setMinUnitPrice(itemOrg.getMinUnitPrice());
            }
            return changeItem;
        }).collect(Collectors.toList());
        boolean updateResult = omsOrderItemService.updateBatchById(changeItems);
        if (!updateResult) {
            return Result.error("订单明细数量修改失败！");
        } else {
            return Result.ok("成功！");
        }
    }

    /**
     * 修改商品价格
     *
     * @return
     */
    private Result updateOrderItemPrice(List<OmsOrderItem> collect, OmsOrderModel orderVO) {

        List<OmsOrderItem> changeItems = collect.stream().map(orderItem -> {
            OmsOrderItem changeItem = new OmsOrderItem();
            changeItem.setId(orderItem.getId());
            OmsOrderItem newItemOrg = (OmsOrderItem) orderVO.getItemMap().get(-orderItem.getId());
            OmsOrderItem itemOrg = (OmsOrderItem) orderVO.getItemMap().get(orderItem.getId());
            if (itemOrg != null) {
                if (newItemOrg != null) {
                    //有赠品
                    itemOrg.setGiftQuantity(newItemOrg.getProductQuantity());
                    itemOrg.setProductQuantity(itemOrg.getProductQuantity() + newItemOrg.getProductQuantity());
                } else {
                    //没有赠品时
                    itemOrg.setGiftQuantity(orderItem.getGiftQuantity());
                    itemOrg.setProductQuantity(itemOrg.getProductQuantity() + orderItem.getGiftQuantity());
                }
            } else if (itemOrg == null) {
                itemOrg = orderItem;
                if (newItemOrg != null) {
                    Integer gift = itemOrg.getGiftQuantity() - newItemOrg.getProductQuantity();
                    itemOrg.setGiftQuantity(newItemOrg.getProductQuantity());
                    itemOrg.setProductQuantity(itemOrg.getProductQuantity() - gift);
                }
            }
            changeItem.setPromotionName("后台改价：" + itemOrg.getNeedPayAmount());
            changeItem.setRealAmount(itemOrg.getNeedPayAmount());
            changeItem.setProductQuantity(itemOrg.getProductQuantity());
            changeItem.setGiftQuantity(itemOrg.getGiftQuantity());
            BigDecimal totalRealAmount = itemOrg.getRealAmount().multiply(new BigDecimal(itemOrg.getProductQuantity() - itemOrg.getGiftQuantity()));
            changeItem.setTotalRealAmount(itemOrg.getNeedPayAmount());

            return changeItem;
        }).collect(Collectors.toList());
        boolean b = omsOrderItemService.updateBatchById(changeItems);
        if (!b) {
            return Result.error("订单明细价格修改失败");
        } else {
            return Result.ok("成功!");
        }
    }

    //记录订单日志
    private Result saveOrderTrace(OmsOrderModel orderVO, LoginUser sysUser) {
        OmsOrderTrace omsOrderTrace = new OmsOrderTrace();
        omsOrderTrace.setOrderId(orderVO.getOrderId());
        omsOrderTrace.setCreateBy(sysUser.getRealname());
        omsOrderTrace.setCreateTime(new Date());
        if (orderVO.getStatus().equals(1)) {
            omsOrderTrace.setLabel("跟单员审核通过");
            omsOrderTrace.setContent("通过");
        } else if (orderVO.getStatus() == 8) {
            omsOrderTrace.setLabel("跟单员审核不通过：" + orderVO.getNote());
            omsOrderTrace.setContent(orderVO.getNote());
        }
        omsOrderTraceService.save(omsOrderTrace);

        return Result.ok("成功!");
    }


    /**
     * 修改订单状态及付款金额
     */
    private Result updateOrder(OmsOrderModel orderVO, LoginUser sysUser, boolean needCalculateOrderAmount, OmsOrder order) {
        OmsOrder changeOrder = omsOrderService.getById(orderVO.getOrderId());
        if (changeOrder.getPartnerId() == null || changeOrder.getPartnerId().equals(0L)) {
            throw new FlycoException("订单商户编码为空！");
        }
        //获取订单配置，判断订单是否需要传sap
        OmsOrderSetting orderSetting = omsOrderSettingService.getOne();
        if (orderSetting != null && orderSetting.getToSapFlag() == 1) {
            /*判断订单金额和可用余额，如果可用余额足够，传SAP,修改复审时间，否则不传 by martin 2024-06-05*/
            BigDecimal balance = sapTaskService.getBalance(order.getStoreId().toString());
            //如果此经销商订单前有初审的订单，需要扣除其占用金额 by martin 2024-08-21 14:23
            List<OmsOrder> orderList = omsOrderService.getAuditOrderList(changeOrder);
            if (!orderList.isEmpty()) {
                for (OmsOrder o : orderList) {
                    if (o.getPayAmount() != null) {
                        balance = balance.subtract(o.getPayAmount());
                    }
                }
            }
            BigDecimal zero = BigDecimal.ZERO;
            if (balance.compareTo(changeOrder.getPayAmount()) >= 0 && balance.compareTo(zero) > 0 && changeOrder.getPayAmount().compareTo(zero) > 0) {
                if (orderVO.getStatus() == 1) {
                    log.info("订单手工复审-订单号:" + changeOrder.getOrderNo() + "-账户余额:" + balance + "-订单金额:" + changeOrder.getPayAmount());
                    Map<String, String> result = sapTaskService.toSapOrder(changeOrder, order.getId(), sysUser.getRealname());
                    if (!"S".equalsIgnoreCase(result.get("type"))) {
                        log.info("推送sap订单失败:" + result.get("originalResult"));
                        throw new FlycoException("推送sap订单失败：" + result.get("message"));
                    }
                }
                changeOrder.setCheckTime(new Date());
            } else {
                //余额不足时候只初审
                changeOrder.setStatus(5);
            }
        } else {
            //不传sap只初审
            changeOrder.setStatus(5);
        }
        List<OmsOrderItem> newItems = omsOrderItemService.selectByMainId(orderVO.getOrderId());
        BigDecimal payAmount = newItems.stream().map(OmsOrderItem::getTotalRealAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        changeOrder.setPayAmount(payAmount);
        BigDecimal totalAmount = newItems.stream().map(OmsOrderItem::getTotalProductAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        changeOrder.setTotalAmount(totalAmount);
        changeOrder.setUpdateTime(new Date());
        changeOrder.setProductDiscountAmount(newItems.stream().map(OmsOrderItem::getProductDiscountAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
        changeOrder.setPromotionDiscountAmount(newItems.stream().map(OmsOrderItem::getPromotionDiscountAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
        changeOrder.setMissionDiscountAmount(newItems.stream().map(OmsOrderItem::getMissionDiscountAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
        changeOrder.setAdjustDiscountAmount(newItems.stream().map(OmsOrderItem::getAdjustDiscountAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
        changeOrder.setFixedDiscountAmount(newItems.stream().map(OmsOrderItem::getFixedDiscountAmount).reduce(BigDecimal.ZERO, BigDecimal::add));

        BigDecimal discountAmount = BigDecimal.ZERO;
        if (changeOrder.getFixedDiscountAmount() != null && changeOrder.getFixedDiscountAmount() != BigDecimal.ZERO) {
            discountAmount = discountAmount.add(changeOrder.getFixedDiscountAmount());
        }
        if (changeOrder.getMissionDiscountAmount() != null && changeOrder.getMissionDiscountAmount() != BigDecimal.ZERO) {
            discountAmount = discountAmount.add(changeOrder.getMissionDiscountAmount());
        }
        if (changeOrder.getProductDiscountAmount() != null && changeOrder.getProductDiscountAmount() != BigDecimal.ZERO) {
            discountAmount = discountAmount.add(changeOrder.getProductDiscountAmount());
        }
        if (changeOrder.getPromotionDiscountAmount() != null && changeOrder.getPromotionDiscountAmount() != BigDecimal.ZERO) {
            discountAmount = discountAmount.add(changeOrder.getPromotionDiscountAmount());
        }
        if (changeOrder.getAdjustDiscountAmount() != null && changeOrder.getAdjustDiscountAmount() != BigDecimal.ZERO) {
            discountAmount = discountAmount.add(changeOrder.getAdjustDiscountAmount());
        }
        changeOrder.setDiscountAmount(discountAmount);
        changeOrder.setId(orderVO.getOrderId());
        changeOrder.setApplyTime(new Date());
        changeOrder.setApplyBy(sysUser.getRealname());
        changeOrder.setProcessTag("后台改价及订单状态修改：" + sysUser.getRealname());
        //changeOrder.setNote(orderVO.getNote());

        //任意一个>0，表示有使用折扣
        if (changeOrder.getProductDiscountAmount().compareTo(BigDecimal.ZERO) > 0
                || changeOrder.getPromotionDiscountAmount().compareTo(BigDecimal.ZERO) > 0
                || changeOrder.getMissionDiscountAmount().compareTo(BigDecimal.ZERO) > 0
                || changeOrder.getAdjustDiscountAmount().compareTo(BigDecimal.ZERO) > 0) {

            //折扣使用记录
            OmsOrderDiscountRecord omsOrderDiscountRecord = new OmsOrderDiscountRecord();
            omsOrderDiscountRecord.setOrderId(orderVO.getOrderId());
            omsOrderDiscountRecord.setProductAmount(changeOrder.getProductDiscountAmount());
            omsOrderDiscountRecord.setPromotionAmount(changeOrder.getPromotionDiscountAmount());
            omsOrderDiscountRecord.setMissionAmount(changeOrder.getMissionDiscountAmount());
            omsOrderDiscountRecord.setAdjustAmount(changeOrder.getAdjustDiscountAmount());
            omsOrderDiscountRecord.setUseStatus(1);//已使用
            omsOrderDiscountRecord.setCreateBy(sysUser.getUsername());
            omsOrderDiscountRecord.setCreateTime(DateTime.now());
            omsOrderDiscountRecordService.save(omsOrderDiscountRecord);
        }
        boolean update = omsOrderService.updateById(changeOrder);
        if (!update) {
            return Result.fail("数据过期，请刷新页面重试");
        }
        return Result.ok("成功!");
    }


    /**
     * 改运费
     *
     * @param vueOrder
     * @return
     */
    @AutoLog(value = "订单-修改运费")
    @PutMapping(value = "/editFreight")
    public Result<?> editFreight(@RequestBody OmsOrder vueOrder) {
        OmsOrder order = omsOrderService.getById(vueOrder.getId());
        if (null == order || 7 != order.getStatus()) return Result.error("当前状态不可修改价格");
        if (null == vueOrder.getFreightAmount()) return Result.error("运费无需修改");
        OmsOrder changeOrder = new OmsOrder();
        changeOrder.setFreightAmount(vueOrder.getFreightAmount());
        BigDecimal noFreightAmount = order.getPayAmount().subtract(order.getFreightAmount() == null ? BigDecimal.ZERO : order.getFreightAmount());
        changeOrder.setPayAmount(noFreightAmount.add(vueOrder.getFreightAmount()));
        LambdaQueryWrapper<OmsOrder> query = new LambdaQueryWrapper<>();
        query.eq(OmsOrder::getId, vueOrder.getId());
        query.in(OmsOrder::getStatus, Arrays.asList(0));
        query.in(OmsOrder::getPayStatus, Arrays.asList(2));
        Boolean b = omsOrderService.update(changeOrder, query);
        if (b) {
            return Result.ok("修改运费成功!");
        }
        return Result.error("修改运费失败");
    }

    /**
     * 通过id取消订单
     *
     * @param vueOrder
     * @return
     */
    @AutoLog(value = "订单-取消订单")
    @PutMapping(value = "/cancel")
    public Result<?> cancel(@RequestBody OmsOrder vueOrder) {
        OmsOrder order = omsOrderService.getById(vueOrder.getId());
        if (null == order || (
                0 != order.getStatus() && 1 != order.getStatus()
                        && 6 != order.getStatus() && 9 != order.getStatus()
                        && 10 != order.getStatus() && 7 != order.getStatus()
        )) {
            return Result.error("当前订单不可以取消");
        }

        List<OmsOrderItem> orderItems = omsOrderItemService.selectByMainId(vueOrder.getId());
        //判断是否存在部分发货的情况，如果有，不允许取消
        Long sendCount = orderItems.stream().filter(o -> o.getSendQty().compareTo(BigDecimal.ZERO) > 0).count();
        if (sendCount > 0) {
//            return Result.error("订单已部分发货，不可以取消！");
        }

        OmsOrder changeOrder = new OmsOrder();
        changeOrder.setStatus(4);
        changeOrder.setPayStatus(0);
        changeOrder.setProductStatus(0);

        if (order.getStatus().equals(1)) {
            cancelPayNotSendOrder(changeOrder, vueOrder);
        } else {
            LambdaQueryWrapper<OmsOrder> query = new LambdaQueryWrapper<>();
            query.eq(OmsOrder::getId, vueOrder.getId());
            query.in(OmsOrder::getStatus, Arrays.asList(0, 1, 6, 7, 9, 10));
            Boolean b = omsOrderService.update(changeOrder, query);
        }

        Date date = new Date();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        OmsOrderTrace omsOrderTrace = new OmsOrderTrace();
        omsOrderTrace.setOrderId(vueOrder.getId());
        omsOrderTrace.setLabel("已取消");
        omsOrderTrace.setContent("你的订单已取消，取消人：" + sysUser.getRealname());
        omsOrderTrace.setCreateTime(date);
        omsOrderTraceService.save(omsOrderTrace);

        //记录订单取消表，同步给旺店通
        omsOrderCancelService.save(vueOrder.getId());


        //订单取消后，扣除订单确认时增加的购买数量
        updateProductStock(order.getId(), 2);

        return Result.ok("取消成功!");
    }


    /**
     * 通过id删除订单
     *
     * @param vueOrder
     * @return
     */
    @AutoLog(value = "订单-删除订单")
    @PutMapping(value = "/remove")
    public Result<?> remove(@RequestBody OmsOrder vueOrder) {
        OmsOrder order = omsOrderService.getById(vueOrder.getId());
        if (null == order || (0 != order.getStatus() && 4 != order.getStatus() && 8 != order.getStatus())) {
            return Result.error("当前订单不可以删除");
        }
        //List<OmsOrderItem> orderItems = omsOrderItemService.selectByMainId(vueOrder.getId());
        //判断是否存在部分发货的情况，如果有，不允许取消
        //Long sendCount = orderItems.stream().filter(o -> o.getSendQty().compareTo(BigDecimal.ZERO) > 0).count();
        //if (sendCount > 0) {
        //return Result.error("订单已部分发货，不可以取消！");
        //}

        OmsOrder changeOrder = new OmsOrder();
        changeOrder.setDeleteStatus(1);
        LambdaQueryWrapper<OmsOrder> query = new LambdaQueryWrapper<>();
        query.eq(OmsOrder::getId, vueOrder.getId());
        query.in(OmsOrder::getStatus, Arrays.asList(0, 1, 4, 8));
        Boolean b = omsOrderService.update(changeOrder, query);

        Date date = new Date();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        OmsOrderTrace omsOrderTrace = new OmsOrderTrace();
        omsOrderTrace.setOrderId(vueOrder.getId());
        omsOrderTrace.setLabel("已取消");
        omsOrderTrace.setContent("你的订单已删除，删除人：" + sysUser.getRealname());
        omsOrderTrace.setCreateTime(date);
        omsOrderTraceService.save(omsOrderTrace);

        return Result.ok("取消成功!");
    }


    /**
     * 取消待出库订单
     */
    private Result<?> cancelPayNotSendOrder(OmsOrder changeOrder, OmsOrder vueOrder) {

        LambdaQueryWrapper<OmsOrder> query = new LambdaQueryWrapper<>();
        query.eq(OmsOrder::getId, vueOrder.getId());
        query.eq(OmsOrder::getStatus, 1);
        query.eq(OmsOrder::getPayStatus, 4);
        query.eq(OmsOrder::getProductStatus, 3);
        Boolean b = omsOrderService.update(changeOrder, query);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //废除出库单
        cancelStockOut(vueOrder, sysUser);
        return Result.ok("取消成功!");
    }


    private void cancelStockOut(OmsOrder omsOrder, LoginUser sysUser) {

        StmBizInoutRelation changeRelation = new StmBizInoutRelation();
        changeRelation.setStatus(4);
        changeRelation.setUpdateTime(DateTime.now());
        changeRelation.setUpdateBy(sysUser.getRealname());

        LambdaQueryWrapper<StmBizInoutRelation> query = new LambdaQueryWrapper<>();
        query.eq(StmBizInoutRelation::getOrderId, omsOrder.getId());
        query.eq(StmBizInoutRelation::getStatus, 1);
        query.eq(StmBizInoutRelation::getPartnerId, sysUser.getPartnerId());
        stmBizInoutRelationService.update(changeRelation, query);
    }


    /**
     * 批量确认订单
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "订单-订单确认")
    @PostMapping(value = "/confirmBatch")
    public Result<?> confirmBatch(@RequestBody String[] ids) {
        omsOrderService.confirmBatch(Arrays.asList(ids));
        return Result.ok("订单确认成功！");
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        omsOrderService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.omsOrderService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        OmsOrder omsOrder = omsOrderService.getById(id);
        return Result.ok(omsOrder);
    }

    /**
     * 通过id查询商品信息
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryOmsOrderItemByMainId")
    public Result<?> queryOmsOrderItemListByMainId(@RequestParam(name = "id", required = true) String id) {
        OmsOrder order = omsOrderService.getById(id);
        if (order != null && order.getStatus().equals(0)) {
            //因为4100暂时没有库存，测试期间暂时不更新库存
            sapTaskService.toSapStock(id, order.getPartnerId());//更新库存
        }
        List<OmsOrderItem> items = omsOrderItemService.selectByMainId(id);
        List<OmsOrderItem> newItemList = new ArrayList<>();
        OmsOrderSetting orderSetting = omsOrderSettingService.getOne();
        BigDecimal maxDiscount = orderSetting == null ? BigDecimal.valueOf(90) : orderSetting.getDiscountLimit();
        for (OmsOrderItem item : items) {
            if (item.getGiftQuantity() != null && item.getGiftQuantity() > 0) {
                //现在ProductQuantity 是购买数量+赠品数量总和
                item.setProductQuantity(item.getProductQuantity() - item.getGiftQuantity());
                newItemList.add(item);
                OmsOrderItem giftRow = new OmsOrderItem();
                BeanUtils.copyProperties(item, giftRow);
                giftRow.setProductQuantity(item.getGiftQuantity());
                giftRow.setOrderProductType("1");
                giftRow.setGiftQuantity(0);
                giftRow.setRealAmount(new BigDecimal(0));
                giftRow.setTotalRealAmount(new BigDecimal(0));
                giftRow.setId(-item.getId());
                newItemList.add(giftRow);
            } else {
                //非初审订单不用查询固定折扣
                if (order != null && order.getStatus().equals(0)) {
                    sapTaskService.getSapFixedDiscount(order, item);
                }
                if (item.getFixedDiscountRate() == null || item.getFixedDiscountRate().compareTo(BigDecimal.ZERO) == 0) {
                    item.setFixedDiscountRate(BigDecimal.valueOf(0));
                }
                if (item.getFixedDiscountAmount() == null || item.getFixedDiscountAmount().compareTo(BigDecimal.ZERO) == 0) {
                    item.setFixedDiscountAmount(BigDecimal.valueOf(0));
                }
                if (item.getTotalRealAmount() != null && item.getTotalProductAmount() != null && item.getTotalRealAmount().compareTo(item.getTotalProductAmount()) == 0 && item.getFixedDiscountAmount().compareTo(new BigDecimal(0)) > 0) {
                    item.setTotalRealAmount(item.getTotalRealAmount().subtract(item.getFixedDiscountAmount()));
                }
                newItemList.add(item);
            }
        }

        List<String> skuCodeList = newItemList.stream().map(OmsOrderItem::getProductSkuCode).collect(Collectors.toList());
        List<OmsOrderItem> itemStockList = omsOrderItemService.getProductOccupation(order.getId(), order.getPartnerId());
        List<StmJdWmsStock> stockList = wmsStockService.getBySkuCodeList(skuCodeList, order.getPartnerId());
        StmJdWmsStock wmsStock = new StmJdWmsStock();
        for (OmsOrderItem item : newItemList) {
            item.setMaxDiscount(maxDiscount);
            /* 后台可能设置为0，不做限制
            if (order != null && order.getStatus().equals(0) && isNewOrder && item.getSendQty().compareTo(BigDecimal.ZERO) == 0) {
                Integer boxQty = item.getMinUnitQuantity() / item.getProductSkuSpec();
                item.setSendQty(new BigDecimal(boxQty));
            }
            if (order != null && order.getStatus().equals(0) && isNewOrder && item.getSendProQty() == 0) {
                item.setSendProQty(item.getMinUnitQuantity());
            }*/
            item.setMinUnitPrice(item.getProductPrice());//单价
            item.setProductPrice(item.getProductPrice().multiply(new BigDecimal(item.getProductSkuSpec())));//箱价
            if (!StringUtils.isEmpty(item.getOrderProductType())) {
                item.setOrderProductType_dictText(dictService.queryDictTextByKey("order_product_type", item.getOrderProductType()));
            }
            //虚拟出来的赠品就不用计算库存和冻结数量了。
            if (item.getId() > 0) {
                //获取库存
                Optional<StmJdWmsStock> wmsStockOptional = stockList.stream().filter(x -> x.getSkuCode().equals(item.getProductSkuCode())).findFirst();
                if (wmsStockOptional.isPresent()) {
                    wmsStock = wmsStockOptional.get();
                }
                Integer occupyQty = 0;
                Integer boxOccupyQty = 0;
                if (wmsStock.getId() != null) {
                    String skuCode = wmsStock.getSkuCode();
                    List<OmsOrderItem> itemLIst = itemStockList.stream().filter(x -> x.getProductSkuCode().equals(skuCode)).collect(Collectors.toList());
                    if (!itemLIst.isEmpty()) {
                        occupyQty = itemLIst.get(0).getSendProQty();
                        boxOccupyQty = itemLIst.get(0).getSendProQty() / item.getProductSkuSpec();
                    }
                }
                item.setStock(wmsStock.getId() == null ? 0 : wmsStock.getStock() / item.getProductSkuSpec() - boxOccupyQty);
                item.setStockUnit(wmsStock.getId() == null ? 0 : wmsStock.getStock() - occupyQty);
            }
            if (item.getSendProQty().equals(0)) {
                item.setDiscountAmount(BigDecimal.ZERO);
                item.setFixedDiscountAmount(BigDecimal.ZERO);
                item.setTotalRealAmount(BigDecimal.ZERO);
            }
            item.setOrderNo(order.getOrderNo());
        }
        return Result.ok(newItemList);
    }

    /**
     * 通过id查询发票信息
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryOmsOrderInvoiceByMainId")
    public Result<?> queryOmsOrderInvoiceListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<OmsOrderInvoice> invoices = omsOrderInvoiceService.selectByMainId(id);
        for (OmsOrderInvoice invoice : invoices) {
            if (!StringUtils.isEmpty(invoice.getInvoiceType()))
                invoice.setInvoiceType_dictText(dictService.queryDictTextByKey("invoice_type", invoice.getInvoiceType()));
            if (!StringUtils.isEmpty(invoice.getInvoiceStatus()))
                invoice.setInvoiceStatus_dictText(dictService.queryDictTextByKey("invoice_status", invoice.getInvoiceStatus().toString()));
            if (!StringUtils.isEmpty(invoice.getDeleteStatus()))
                invoice.setDeleteStatus_dictText(dictService.queryDictTextByKey("yn", invoice.getDeleteStatus().toString()));
        }
        return Result.ok(invoices);
    }

    /**
     * 查询订单跟踪信息
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单-查询订单跟踪信息")
    @GetMapping(value = "/queryOmsOrderTrace")
    public Result<?> queryOmsOrderTrace(@RequestParam(name = "id", required = true) String id) {
        OmsOrder omsOrder = omsOrderService.getById(id);
        if (null == omsOrder) return Result.error("查询的订单不存在");
        LambdaQueryWrapper<OmsOrderTrace> query = new LambdaQueryWrapper<>();
        query.eq(OmsOrderTrace::getOrderId, id);
        if (oConvertUtils.isNotEmpty(omsOrder.getDeliverySn())) {
            query.or();
            query.eq(OmsOrderTrace::getTraceNo, omsOrder.getDeliverySn());
        }
        query.orderByDesc(OmsOrderTrace::getId);
        List<OmsOrderTrace> traceList = omsOrderTraceService.list(query);
        return Result.ok(traceList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param omsOrder
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, OmsOrder omsOrder) {
        if (omsOrder.getCompanyName() != null && omsOrder.getCompanyName().indexOf("*") == -1) {
            omsOrder.setCompanyName("*" + omsOrder.getCompanyName() + "*");
        }

        List<Integer> inStatusList = new ArrayList<>();
        if (omsOrder.getStatus() != null && omsOrder.getStatus().equals(1)) {
            inStatusList.add(1);
            inStatusList.add(11);
            omsOrder.setStatus(null);
        }

        List<Integer> statusList = new ArrayList<>();
        statusList.add(4);
        statusList.add(8);

        QueryWrapper<OmsOrder> queryWrapper = QueryGenerator.initQueryWrapper(omsOrder, request.getParameterMap());
        queryWrapper.ne("store_id", 0);
        queryWrapper.ne("delete_status", 1);
        if (StringUtils.isEmpty(omsOrder.getOrderType())) {
            queryWrapper.in("order_type", 0, 1);
        }
        if (!StringUtils.isEmpty(omsOrder.getSaleUserName())) {
            queryWrapper.eq("sale_user_name", omsOrder.getSaleUserName());
        }
        //默认过滤取消和退回状态的订单
        if (!statusList.contains(omsOrder.getStatus())) {
            queryWrapper.notIn("status", statusList);
        }
        //如果筛选复审的时候，把已复审未提货的也带出来
        if (!inStatusList.isEmpty()) {
            queryWrapper.in("status", inStatusList);
        }
        queryWrapper.orderByDesc("id");
        Page<OmsOrder> page = new Page<OmsOrder>(1, 100000);
        IPage<OmsOrder> pageList = omsOrderService.page(page, queryWrapper);
        List<OmsFlycoOrderExcel> omsOrderExcelList = new ArrayList<>();
        if (pageList.getTotal() > 0) {
            BigDecimal amount = BigDecimal.ZERO;
            for (OmsOrder order : pageList.getRecords()) {
                if (oConvertUtils.isNotEmpty(order.getStoreId())) {
                    order.setStoreId_dictText(stmStoreInfoService.getByStoreId(order.getStoreId()).getName());
                }
                OmsFlycoOrderExcel omsOrderExcel = new OmsFlycoOrderExcel();
                BeanUtils.copyProperties(order, omsOrderExcel);
                omsOrderExcel.setPayTime(omsOrderExcel.getCheckTime());
                amount = amount.add(order.getPayAmount());
                omsOrderExcelList.add(omsOrderExcel);
            }
            OmsFlycoOrderExcel omsOrderExcel = new OmsFlycoOrderExcel();
            omsOrderExcel.setStockName("合计：");
            omsOrderExcel.setPayAmount(amount);
            omsOrderExcelList.add(omsOrderExcel);
        }

        //LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //Step.3 调用EasyPoi导出Excel
        ModelAndView mv = new ModelAndView(new EntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "经销商订单");
        mv.addObject(NormalExcelConstants.CLASS, OmsFlycoOrderExcel.class);
        //mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("经销商订单列表", "导出人:" + sysUser.getRealname(), "经销商订单"));
        ExportParams params = new ExportParams();
        params.setStyle(CustomerExcelExportStyler.class);
        mv.addObject(NormalExcelConstants.PARAMS, params);
        mv.addObject(NormalExcelConstants.DATA_LIST, omsOrderExcelList);
        return mv;
    }


    /**
     * 导出excel
     *
     * @param request
     * @param omsOrder
     */
    @RequestMapping(value = "/exportXlsForFinance")
    public ModelAndView exportXlsForFinance(HttpServletRequest request, OmsOrder omsOrder) {
        // Step.1 组装查询条件
        QueryWrapper<OmsOrder> queryWrapper = QueryGenerator.initQueryWrapper(omsOrder, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //要么导出选中的，要么空
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        //Step.2 获取导出数据
        List<OmsOrderPage> pageList = new ArrayList<OmsOrderPage>();
        List<OmsOrder> omsOrderList = omsOrderService.list(queryWrapper);

        List<StmStoreInfo> storeInfos = stmStoreInfoService.list();
        Map<Long, String> storeInfoMaps = storeInfos.stream().collect(Collectors.toMap(StmStoreInfo::getStoreId, StmStoreInfo::getName, (key1, key2) -> key2));

        for (OmsOrder temp : omsOrderList) {
            if (storeInfoMaps.containsKey(temp.getStoreId())) {
                temp.setStoreId_dictText(storeInfoMaps.get(temp.getStoreId()));
            }
            OmsOrderPage vo = new OmsOrderPage();
            BeanUtils.copyProperties(temp, vo);
            List<OmsOrderItem> omsOrderItemList = omsOrderItemService.selectByMainId(temp.getId());
            vo.setOmsOrderItemList(omsOrderItemList);
            List<OmsOrderInvoice> omsOrderInvoiceList = omsOrderInvoiceService.selectByMainId(temp.getId());
            vo.setOmsOrderInvoiceList(omsOrderInvoiceList);
            pageList.add(vo);
        }
        //Step.3 调用AutoPoi导出Excel
        ModelAndView mv = new ModelAndView(new EntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "订单管理");
        mv.addObject(NormalExcelConstants.CLASS, OmsOrderPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("订单管理数据", "导出人:" + sysUser.getRealname(), "订单管理"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }


    /**
     * 订单明细导出excel
     */
    @RequestMapping(value = "/exportOrderItemXls")
    public ModelAndView exportOrderItemXls(HttpServletRequest request, OmsOrder omsOrder) {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<OmsOrderItemExcel> orderItemExcels = omsOrderItemService.getOrderItemList(omsOrder);

        //Step.3 调用AutoPoi导出Excel
        ModelAndView mv = new ModelAndView(new EntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "订单明细报表");
        mv.addObject(NormalExcelConstants.CLASS, OmsOrderItemExcel.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("订单明细报表", "导出人:" + sysUser.getRealname(), "订单明细报表"));
        mv.addObject(NormalExcelConstants.DATA_LIST, orderItemExcels);
        return mv;
    }


    /**
     * 导出excel模板
     *
     * @param request
     * @param omsOrder
     */
    @RequestMapping(value = "/exportTemplateXls")
    public ModelAndView exportTemplateXls(HttpServletRequest request, OmsOrder omsOrder) {
        // Step.1 组装查询条件
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //要么导出选中的，要么空

        //Step.2 获取导出数据
        List<OmsOrderImportPage> pageList = new ArrayList<OmsOrderImportPage>();
        //Step.3 调用AutoPoi导出Excel
        ModelAndView mv = new ModelAndView(new EntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "订单管理");
        mv.addObject(NormalExcelConstants.CLASS, OmsOrderImportPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("订单管理数据", "导出人:" + sysUser.getRealname(), "订单管理"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        String ip = IPUtils.getIpAddr(request);
        if (StringUtils.isEmpty(ip) && ip.length() > 15) {
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }

        List<PmsProductPriceRegulate> priceRegulates = pmsProductPriceRegulateService.list();
        Map<String, PmsProductPriceRegulate> regulateMap = priceRegulates.stream().collect(Collectors.toMap(PmsProductPriceRegulate::getSkuCode, Function.identity(), (key1, key2) -> key2));

        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<OmsOrderImportPage> list = ExcelImportUtil.importExcel(file.getInputStream(), OmsOrderImportPage.class, params);
                if (oConvertUtils.isEmpty(list) || list.size() == 0) return Result.error("文件导入失败: 请维护记录");

                List<Long> memberIds = list.stream().map(OmsOrderImportPage::getMemberId).distinct().collect(Collectors.toList());
                List<UmsMember> memberList = umsMemberService.listByIds(memberIds);
                List<UmsMember> errorMembers = memberList.stream().filter(r -> !Objects.equals(r.getRole(), 5)).collect(Collectors.toList());
                if (errorMembers.size() > 0) {
                    return Result.error("文件导入失败: 用户" + Joiner.on(",").join(errorMembers.stream().map(UmsMember::getId).collect(Collectors.toList())) + "不是团长");
                }
                Map<Long, UmsMember> memberMap = memberList.stream().collect(Collectors.toMap(UmsMember::getId, Function.identity(), (key1, key2) -> key2));
                Map<String, List<OmsOrderImportPage>> listMap = list.stream().collect(Collectors.groupingBy(e -> fetchGroupKey(e)));
                List<Long> storeIds = list.stream().map(OmsOrderImportPage::getStoreId).distinct().collect(Collectors.toList());
                List<PmsProductSkuForOrderVO> productSkuForOrderVOS = pmsProductService.queryProductSkuList(storeIds, null, null);
                Map<String, List<PmsProductSkuForOrderVO>> skuMap = productSkuForOrderVOS.stream().collect(Collectors.groupingBy(e -> fetchGroupSkuKey(e)));
                //Integer totalSize = 0;
                List<OmsOrderImportModel> orderImportModels = new ArrayList<>();
                for (Map.Entry<String, List<OmsOrderImportPage>> listEntry : listMap.entrySet()) {
                    String[] storeMembers = listEntry.getKey().split("#");
                    Long storeId = Long.valueOf(storeMembers[0]);
                    Long memberId = Long.valueOf(storeMembers[1]);
                    UmsMember member = memberMap.get(memberId);
                    if (oConvertUtils.isEmpty(member)) return Result.error("文件导入失败: 订单所属用户不存在");
                    OmsOrderBatch orderBatch = new OmsOrderBatch();
                    orderBatch.setMemberId(memberId);
                    omsOrderBatchService.save(orderBatch);
                    String batchNote = "";
                    List<OmsOrderImportPage> pageList = listEntry.getValue();
                    for (OmsOrderImportPage page : pageList) {
                        Boolean flag = false;//商品校验标识
                        batchNote = page.getBatchNote();
                        List<OmsOrderItem> items = new ArrayList<>();
                        List<OmsOrderItemModel> itemModels = page.getOmsOrderItemList();
                        for (OmsOrderItemModel item : itemModels) {
                            String key = "" + storeId + "#" + item.getProductSn();
                            if (skuMap.containsKey(key)) {
                                PmsProductSkuForOrderVO vo = skuMap.get(key).get(0);
                                item.setProductId(vo.getId());
                                item.setProductPic(vo.getPic());
                                item.setProductSkuId(vo.getSkuId());
                                item.setProductSkuCode(vo.getSkuCode());
                                item.setSapItemCode(vo.getSapItemCode());
                                item.setProductCategoryId(vo.getProductCategoryId());
                                item.setProductBrand(vo.getBrandName());
                                item.setPromotionName("后台导单");
                                item.setPromotionAmount(BigDecimal.ZERO);
                                item.setCouponAmount(BigDecimal.ZERO);
                                item.setIntegrationAmount(BigDecimal.ZERO);
                                item.setRealAmount(item.getProductPrice());
                                item.setTotalPromotionAmount(BigDecimal.ZERO);
                                item.setTotalCouponAmount(BigDecimal.ZERO);
                                item.setTotalIntegrationAmount(BigDecimal.ZERO);
                                item.setTotalRedbagAmount(BigDecimal.ZERO);
                                item.setTotalRealAmount(item.getProductPrice().multiply(new BigDecimal(item.getProductQuantity())));
                                if (!Objects.equals(item.getOrderProductType(), "1")) {
                                    if (regulateMap.containsKey(vo.getSkuCode())) {
                                        PmsProductPriceRegulate regulate = regulateMap.get(vo.getSkuCode());
                                        BigDecimal price = regulate.getMinPrice() != null ? regulate.getMinPrice() : regulate.getNormalPrice();
                                        if (item.getProductPrice().compareTo(price) == -1) {
                                            flag = true;
                                        }
                                    }
                                }
                                OmsOrderItem orderItem = new OmsOrderItem();
                                BeanUtils.copyProperties(item, orderItem);
                                items.add(orderItem);
                                /*int productType = item.getProductPrice().compareTo(BigDecimal.ZERO);
                                if (productType < 0) flag = true;
                                if (productType == 0) item.setOrderProductType("1");*/
                            } else {
                                flag = true;
                            }
                        }
                        if (flag)
                            throw new RuntimeException("商品不存在或商品价格低于管控价错误！");
                        OmsOrder po = new OmsOrder();
                        BeanUtils.copyProperties(page, po);
                        po.setId(omsOrderService.generateOrderSn());
                        po.setOrderSn(po.getId());
                        po.setCreateTime(new Date());
                        po.setCustomerType(1);
                        po.setTotalAmount(items.stream().map(OmsOrderItem::getTotalRealAmount).reduce(BigDecimal.ZERO, BigDecimal::add));

                        if (po.getPayAmount().compareTo(po.getTotalAmount()) != 0) {
                            throw new RuntimeException("支付金额与商品金额汇总不一致，请检查！");
                        }
                        po.setEffectiveAmount(BigDecimal.ZERO);
                        po.setFreightAmount(BigDecimal.ZERO);
                        po.setPromotionAmount(BigDecimal.ZERO);
                        po.setIntegrationAmount(BigDecimal.ZERO);
                        po.setCouponAmount(BigDecimal.ZERO);
                        po.setDiscountAmount(BigDecimal.ZERO);
                        po.setRedbagAmount(BigDecimal.ZERO);
                        po.setPayType("wxPay");
                        po.setSourceType("admin");
                        po.setSourceSystem("admin");
                        po.setSourceIp(ip);
                        po.setStatus(0);
                        po.setProductStatus(1);
                        po.setPayStatus(2);
                        po.setReturnStatus(0);
                        po.setOrderType(0);
                        po.setSendType(2);
                        po.setReturnType(0);
                        po.setConfirmStatus(0);
                        po.setBatchId(orderBatch.getId());
                        WSSsdrAddress address = AddressUtil.resolveAddress(po.getReceiverDetailAddress());
                        po.setReceiverProvince(address.getProvince());
                        po.setReceiverCity(address.getCity());
                        po.setReceiverRegion(address.getCounty());
                        OmsOrderAddition addition = new OmsOrderAddition();
                        addition.setId(po.getId());
                        addition.setMemberPhone(member.getMobile());
                        addition.setMemberIcon(member.getAvatar());
                        addition.setMemberNickname(member.getNickname());
                        String productNames = items.stream().map(OmsOrderItem::getProductName).collect(Collectors.joining(","));
                        addition.setProductNames(productNames);
                        OmsOrderImportModel orderImportModel = new OmsOrderImportModel();
                        orderImportModel.setOmsOrder(po);
                        orderImportModel.setOmsOrderItemList(items);
                        orderImportModel.setOmsOrderInvoiceList(null);
                        orderImportModel.setOmsOrderAddition(addition);
                        //omsOrderService.saveMain(po, page.getOmsOrderItemList(),null);
                        //omsOrderAdditionService.save(addition);
                        orderImportModels.add(orderImportModel);
                        //++totalSize;
                        orderBatch.setNote(batchNote);
                        omsOrderBatchService.updateById(orderBatch);
                    }
                }
                if (orderImportModels.size() > 0) {
                    for (OmsOrderImportModel orderImportModel : orderImportModels) {
                        omsOrderService.saveMain(orderImportModel.getOmsOrder(), orderImportModel.getOmsOrderItemList(), orderImportModel.getOmsOrderInvoiceList());
                        omsOrderAdditionService.save(orderImportModel.getOmsOrderAddition());
                    }
                }
                return Result.ok("文件导入成功！数据行数:" + orderImportModels.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

    private static String fetchGroupKey(OmsOrderImportPage item) {
        return item.getStoreId().toString() + "#" + item.getMemberId();
    }

    private static String fetchGroupSkuKey(PmsProductSkuForOrderVO item) {
        return item.getStoreId().toString() + "#" + item.getProductSn();
    }


    @AutoLog(value = "清空小程序端缓存")
    @GetMapping(value = "/clearWxJxCache")
    public Result<?> clearWxJxCache() {
        omsOrderService.clearWxJxCache();
        return Result.ok("完成清理");
    }

    @AutoLog(value = "清空后序端缓存")
    @GetMapping(value = "/clearManageCache")
    public Result<?> clearManageCache() {
        redisUtil.clearAllCache();
        return Result.ok("完成清理");
    }


    /**
     * 通过id取消订单
     *
     * @param vueOrder
     * @return
     */
    @AutoLog(value = "作废订单")
    @PutMapping(value = "/repeal")
    @Transactional
    public Result<?> repeal(@RequestBody OmsOrder vueOrder) {
        OmsOrder order = omsOrderService.getById(vueOrder.getId());
        if (null == order || 3 == order.getStatus()
                || 8 == order.getStatus() || 4 == order.getStatus()
        ) {
            return Result.error("当前订单不可以作废");
        }

        OmsOrder changeOrder = new OmsOrder();
        changeOrder.setStatus(4);
        changeOrder.setPayStatus(0);
        changeOrder.setProductStatus(0);

        LambdaQueryWrapper<OmsOrder> query = new LambdaQueryWrapper<>();
        query.eq(OmsOrder::getId, vueOrder.getId());
        query.in(OmsOrder::getStatus, Arrays.asList(0, 1, 2, 7, 9, 10));
        Boolean b = omsOrderService.update(changeOrder, query);

        if (!b) {
            return Result.error("作废订单失败");
        }

        List<StmBizInoutRelation> inoutRelations = stmBizInoutRelationService.getByOrderId(vueOrder.getId());
        //判断是否已经有出库记录是完成的状态，如果有，则不允许作废。


        if (inoutRelations != null && inoutRelations.size() > 0) {
            //调用接口处理溯源的信息
            List<Long> ids = inoutRelations.stream()
                    .filter(o -> o.getStatus().equals(5) || o.getStatus().equals(7))
                    .map(StmBizInoutRelation::getId)
                    .collect(Collectors.toList());

            deleteBoxTrace(ids);
        }

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //废除出库单
        cancelStockOut(vueOrder, sysUser);

        //记录订单跟踪信息
        omsOrderTraceService.saveTrace(vueOrder.getId(), "作废", "");

        //记录订单取消表，同步给旺店通
        omsOrderCancelService.save(vueOrder.getId());

        return Result.ok("取消成功!");
    }

    //删除溯源信息
    private void deleteBoxTrace(List<Long> bizInoutRelationIds) {
        Date date = new Date();

        PmsBoxTrace pmsBoxTrace = new PmsBoxTrace();
        pmsBoxTrace.setDeleted(1);
        pmsBoxTrace.setUpdater("作废订单");
        pmsBoxTrace.setUpdateTime(date);
        pmsBoxTraceService.update(pmsBoxTrace, Wrappers.lambdaUpdate(PmsBoxTrace.class).eq(PmsBoxTrace::getDeleted, 0).in(PmsBoxTrace::getBizInoutRelationId, bizInoutRelationIds));


        PmsBoxTraceRecord pmsBoxTraceRecord = new PmsBoxTraceRecord();
        pmsBoxTraceRecord.setDeleted(1);
        pmsBoxTraceRecord.setUpdater("作废订单");
        pmsBoxTraceRecord.setUpdateTime(date);
        pmsBoxTraceRecord.setUniCode(date);
        pmsBoxTraceRecordMapper.update(pmsBoxTraceRecord, Wrappers.lambdaUpdate(PmsBoxTraceRecord.class).eq(PmsBoxTraceRecord::getDeleted, 0).in(PmsBoxTraceRecord::getBizInoutRelationId, bizInoutRelationIds));
    }


    @AutoLog(value = "获取订单中已发货数量")
    @GetMapping(value = "/getOrderSendQuantity")
    public Result<?> getOrderSendQuantity(@RequestParam("orderId") String orderId) {
        List<OmsOrderItem> orderItemList = omsOrderItemService.selectByMainId(orderId);
        if (CollectionUtils.isEmpty(orderItemList)) {
            return Result.error("订单明细有误");
        }
        BigDecimal sendCount = BigDecimal.ZERO;
        for (OmsOrderItem item : orderItemList) {
            sendCount = sendCount.add(item.getSendQty());
        }
        return Result.ok(sendCount);
    }

    /**
     * 订单撤销结案
     *
     * @return
     */
    @GetMapping(value = "/revokeClose/{id}")
    public Result<?> revokeClose(@PathVariable("id") String id) {
        OmsOrder omsOrder = omsOrderService.getById(id);
        if (omsOrder == null || !omsOrder.getStatus().equals(3)) {
            return Result.error("订单不存在或者未结案，不能撤销结案！");
        }
        boolean result = sapTaskService.revokeCloseOrder(omsOrder);
        if (result) {
            return Result.ok("撤销结案成功！");
        }
        return Result.error("撤销结案失败！");
    }
}
